package com.dach.as.CheckDsk;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class Mail {

	
	public static boolean DEBUG = false;
	
	
	
	public static void sendMail(String smtpHost,String username,String password,String senderAddress,String recipientsAddress,String subject,String text, boolean requireAuth ) throws Exception {
		MailAuthenticator auth = new MailAuthenticator(username, password);
		
		Properties properties = new Properties();
		
		properties.put("mail.smtp.host", smtpHost);
		
		if (requireAuth)
			properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable","true");
		
		Session session = Session.getDefaultInstance(properties, auth);
		
		if (DEBUG)
			session.setDebug(true);
		
		Message msg = new MimeMessage(session); 
		msg.setFrom(new InternetAddress(senderAddress));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( recipientsAddress, false));
	
		msg.setSubject(subject);
		msg.setText(text);
		
		msg.setSentDate(new Date());
		
		Transport.send(msg);
	}
	
	
	protected static class MailAuthenticator extends Authenticator {
		private final String user;
		private final String password;
		
		public MailAuthenticator(String user, String password) {
			this.user = user;
			this.password = password;
		}
		
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(this.user, this.password);
		}
	}
}
